<template>
    <div class="goods">
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240)"
            :title="isEdit ? `编辑《${goodsInfo.title}》` : '添加商品'"
            sub-title="可返回商品列表"
            @back="backGoodsList"
        />
        <a-menu v-model:selectedKeys="current" mode="horizontal">
            <a-menu-item key="common"> 通用信息 </a-menu-item>
            <a-menu-item key="description"> 详细描述 </a-menu-item>
            <a-menu-item key="attributes"> 商品属性 </a-menu-item>
            <a-menu-item key="specification"> 规格与包装 </a-menu-item>
            <a-menu-item key="album"> 商品相册 </a-menu-item>
        </a-menu>
        <div class="MenuContent" v-if="current && current[0] === 'common'">
            <ARow>
                <ACol span="21">
                    <AForm v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                        <AFormItem label="标题" name="title">
                            <AInput v-model:value="formData.title" />
                        </AFormItem>
                        <AFormItem label="副标题" name="sub_title">
                            <AInput v-model:value="formData.sub_title" />
                        </AFormItem>
                        <AFormItem label="版本" name="goods_version">
                            <AInput v-model:value="formData.goods_version" />
                        </AFormItem>
                        <AFormItem label="所属分类" name="cate_id">
                            <ATreeSelect
                                v-model:value="formData.cate_id"
                                :treeData="
                                    goodsCates.map(item => ({
                                        ...item,
                                        value: item._id,
                                        children: item.children.map(item1 => ({ ...item1, value: item1._id })),
                                    }))
                                "
                            />
                        </AFormItem>
                        <AFormItem name="goods_img" label="图片">
                            <CustomUpload v-model:image="formData.goods_img" />
                        </AFormItem>
                        <AFormItem label="价格" name="shop_price">
                            <AInputNumber v-model:value="formData.shop_price" />
                        </AFormItem>
                        <AFormItem label="原价" name="market_price">
                            <AInputNumber v-model:value="formData.market_price" />
                        </AFormItem>
                        <AFormItem label="状态" name="status">
                            <ARadioGroup v-model:value="formData.status">
                                <ARadioButton :value="1">显示</ARadioButton>
                                <ARadioButton :value="0">隐藏</ARadioButton>
                            </ARadioGroup>
                        </AFormItem>
                        <AFormItem label="标签">
                            <ACheckbox v-model:checked="tagCheckedList[0]">精品</ACheckbox>
                            <ACheckbox v-model:checked="tagCheckedList[1]">热销</ACheckbox>
                            <ACheckbox v-model:checked="tagCheckedList[2]">新品</ACheckbox>
                        </AFormItem>
                    </AForm>
                </ACol>
                <ACol span="3" />
            </ARow>
        </div>
        <div class="MenuContent" v-if="current && current[0] === 'description'">
            <CustomRichText v-model:value="formData.goods_content" />
        </div>
        <div class="MenuContent" v-if="current && current[0] === 'attributes'">
            <ARow>
                <ACol span="21">
                    <AForm v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                        <AFormItem label="颜色" name="goods_color">
                            <ASelect v-model:value="formData.goods_color" :allowClear="true" mode="multiple">
                                <ASelectOption v-for="(item, index) in goodsColorList" :key="index" :value="item._id">{{ item.color_name }}</ASelectOption>
                            </ASelect>
                        </AFormItem>
                        <AFormItem label="关联商品" name="relation_goods">
                            <ASelect v-model:value="formData.relation_goods" mode="multiple" :allowClear="true">
                                <ASelectOption v-for="(item, index) in goodsList" :key="index" :value="item._id"
                                    >{{ item.title }}-{{ item.goods_version }}</ASelectOption
                                >
                            </ASelect>
                        </AFormItem>
                        <AFormItem label="关联赠品" name="relation_goods">
                            <ASelect v-model:value="formData.goods_gift" mode="multiple" :allowClear="true">
                                <ASelectOption v-for="(item, index) in goodsList" :key="index" :value="item._id"
                                    >{{ item.title }}-{{ item.goods_version }}</ASelectOption
                                >
                            </ASelect>
                        </AFormItem>
                        <AFormItem label="关联配件" name="goods_fitting">
                            <ASelect v-model:value="formData.goods_fitting" mode="multiple" :allowClear="true">
                                <ASelectOption v-for="(item, index) in goodsList" :key="index" :value="item._id"
                                    >{{ item.title }}-{{ item.goods_version }}</ASelectOption
                                >
                            </ASelect>
                        </AFormItem>
                        <AFormItem label="更多属性" name="more_attrs">
                            <AInput v-model:value="formData.more_attrs" placeholder="格式:  颜色:红色,白色,黄色 | 尺寸:41,42,43" />
                        </AFormItem>
                        <AFormItem label="Seo关键词" name="goods_keywords">
                            <AInput v-model:value="formData.goods_keywords" />
                        </AFormItem>
                        <AFormItem label="Seo描述" name="goods_desc">
                            <ATextarea v-model:value="formData.goods_desc" />
                        </AFormItem>
                    </AForm>
                </ACol>
                <ACol span="3"> </ACol>
            </ARow>
        </div>
        <div class="MenuContent" v-if="current && current[0] === 'specification'">
            <ARow>
                <ACol span="21">
                    <AForm v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                        <AFormItem label="商品类型">
                            <ASelect @change="goodsTypeChange" v-model:value="goodsTypeId" :allowClear="true">
                                <ASelectOption v-for="(item, index) in goodsTypeList" :key="index" :value="item._id">{{ item.title }}</ASelectOption>
                            </ASelect>
                        </AFormItem>
                        <AFormItem v-for="(item, index) in goodsTypeAttributes" :key="index" :label="item.title" :name="item.title">
                            <AInput v-if="item.attr_type === 'input' || ''" v-model:value="formData.attr_value_list[index]" />
                            <ATextarea v-if="item.attr_type === 'textarea'" v-model:value="formData.attr_value_list[index]" />
                            <ASelect v-if="item.attr_type === 'select'" v-model:value="formData.attr_value_list[index]">
                                <ASelectOption v-for="(option, optionIndex) in item.attr_value.split('\n')" :key="optionIndex" :value="option">{{
                                    option
                                }}</ASelectOption>
                            </ASelect>
                        </AFormItem>
                    </AForm>
                </ACol>
                <ACol span="3" />
            </ARow>
        </div>
        <div class="MenuContent" v-if="current && current[0] === 'album'">
            <ARow>
                <ACol span="21">
                    <AForm v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                        <AFormItem label="相册" name="goods_image_list">
                            <CustomUpload v-model:imageList="formData.goods_image_list" :multiple="true">
                                <template #imageList="{ index }">
                                    <ASelect v-model:value="formData.goodsImageColorList[index]" style="margin-top: 6px">
                                        <ASelectOption value="">请选择颜色</ASelectOption>
                                        <ASelectOption v-for="(item, index) in goodsColorList" :key="index" :value="item._id">{{
                                            item.color_name
                                        }}</ASelectOption>
                                    </ASelect>
                                </template>
                            </CustomUpload>
                        </AFormItem>
                    </AForm>
                </ACol>
                <ACol span="3" />
            </ARow>
        </div>
        <AButton @click="handleSubmit" style="align-self: center" type="primary">提交</AButton>
    </div>
</template>

<script>
import { computed, defineComponent, reactive, toRefs, watch } from "vue";
import CrudPage from "@/components/CrudPage.vue";
import CustomUpload from "@/components/CustomUpload.vue";
import {
    getGoodsCateApi,
    getGoodsColorApi,
    getGoodsTypeApi,
    getGoodsTypeAttributeApi,
    getGoodsApi,
    createGoodsApi,
    getGoodsImageApi,
    updateGoodsApi,
} from "@/api/goods";
import config from "@/config";
import CustomRichText from "@/components/CustomRichText.vue";
import { message } from "ant-design-vue";
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
export default defineComponent({
    components: {
        CrudPage,
        CustomUpload,
        CustomRichText,
    },
    setup() {
        const route = useRoute();
        const router = useRouter();
        const initialFormData = {
            title: "",
            cate_id: "",
            sub_title: "",
            goods_version: "",
            goods_img: "",
            shop_price: null,
            market_price: null,
            status: 1,
            is_best: 0,
            is_hot: 0,
            is_new: 0,
            goods_content: "",
            goods_color: [],
            relation_goods: [],
            goods_gift: [],
            goods_fitting: [],
            goods_image_list: [],
            attr_id_list: [],
            attr_value_list: [],
            more_attrs: "",
            goods_keywords: "",
            goods_desc: "",
            goodsImageColorList: [],
        };
        const state = reactive({
            current: ["common"],
            goodsTypeList: [],
            formData: { ...initialFormData },
            goodsTypeId: "",
            goodsTypeAttributes: [],
            goodsCates: [],
            goodsColorList: [],
            goodsList: [],
            tagCheckedList: [false, false, false],
            goods_id: computed(() => route.query._id),
            goodsInfo: {},
            isEdit: computed(() => config.testObjectId(route.query._id)),
        });
        const goodsTypeChange = goods_type_id => {
            return new Promise(resolve => {
                if (goods_type_id) {
                    getGoodsTypeAttributeApi({ goods_type_id }).then(res => {
                        if (res.code === 200) {
                            state.goodsTypeAttributes = res.data.map(item => ({ ...item, value: "" }));
                            state.formData.attr_value_list = res.data.map(() => "");
                            resolve();
                        }
                    });
                } else {
                    state.goodsTypeAttributes = [];
                }
            });
        };
        const initEditForm = () => {
            const { _id } = route.query;
            getGoodsApi({ _id }).then(res => {
                if (res.code === 200) {
                    const data = res.data.data;
                    if (data && data.length) {
                        state.goodsInfo = data[0];
                        const {
                            title,
                            cate_id,
                            sub_title,
                            goods_version,
                            goods_img,
                            shop_price,
                            market_price,
                            status,
                            is_best,
                            is_hot,
                            is_new,
                            goods_content,
                            goods_color,
                            relation_goods,
                            goods_gift,
                            goods_fitting,
                            goodsAttrs,
                            goods_keywords,
                            more_attrs,
                            goods_desc,
                        } = data[0];
                        state.formData = {
                            ...state.formData,
                            title,
                            cate_id,
                            sub_title,
                            goods_version,
                            goods_img,
                            shop_price,
                            market_price,
                            status,
                            goods_content,
                            goods_color: goods_color.map(item => item._id),
                            relation_goods,
                            goods_gift,
                            goods_fitting,
                            more_attrs,
                            goods_keywords,
                            goods_desc,
                        };
                        state.tagCheckedList = [Boolean(is_best), Boolean(is_hot), Boolean(is_new)];
                        if (goodsAttrs && goodsAttrs.length && goodsAttrs[0].goodsTypeAttribute) {
                            state.goodsTypeId = goodsAttrs[0].goodsTypeAttribute.goods_type_id;
                            goodsTypeChange(state.goodsTypeId).then(() => {
                                state.goodsTypeAttributes.forEach((item, index) => {
                                    goodsAttrs.forEach((item1, index1) => {
                                        if (item._id === item1.goodsTypeAttribute._id) {
                                            state.formData.attr_value_list[index] = item1.attribute_value;
                                        }
                                    });
                                });
                            });
                        }
                    }
                }
            });
            getGoodsImageApi({ goods_id: _id }).then(res => {
                if (res.code === 200) {
                    state.formData.goods_image_list = res.data.map(item => item.img_url);
                    state.formData.goodsImageColorList = res.data.map(item => item.color_id || "");
                }
            });
        };
        watch(
            () => state.goods_id,
            _id => {
                if (_id) {
                    initEditForm();
                }
            },
            {
                immediate: true,
            }
        );
        const getGoodsType = () => {
            getGoodsTypeApi().then(res => {
                if (res.code === 200) {
                    state.goodsTypeList = res.data;
                }
            });
        };
        getGoodsType();
        sessionStorage[config.goodsInfoNavKey] && (state.current = JSON.parse(sessionStorage[config.goodsInfoNavKey]));
        onBeforeRouteLeave(() => {
            sessionStorage.removeItem(config.goodsInfoNavKey);
        });
        watch(
            () => state.current,
            current => {
                sessionStorage[config.goodsInfoNavKey] = JSON.stringify(current);
            }
        );
        const getGoodsCate = () => {
            getGoodsCateApi().then(res => {
                if (res.code === 200) {
                    // state.goodsCates = res.data.reduce((pre, item) => [...pre, item, ...item.children], []);
                    state.goodsCates = res.data;
                }
            });
        };
        getGoodsCate();
        const getGoodsColor = () => {
            getGoodsColorApi().then(res => {
                if (res.code === 200) {
                    state.goodsColorList = res.data;
                }
            });
        };
        getGoodsColor();
        const getGoods = () => {
            getGoodsApi({ page: 1, pageSize: 999 }).then(res => {
                if (res.code === 200) {
                    state.goodsList = res.data.data.filter(item => item._id !== state.goodsInfo._id);
                }
            });
        };
        getGoods();
        const handleSubmit = async () => {
            const [is_best, is_hot, is_new] = state.tagCheckedList;
            const data = {
                ...state.formData,
                is_best: Number(is_best),
                is_hot: Number(is_hot),
                is_new: Number(is_new),
                attr_id_list: state.goodsTypeAttributes.map(item => item._id),
            };
            if (state.isEdit) {
                await updateGoodsApi({ ...data, _id: route.query._id }).then(res => {
                    if (res.code === 200) {
                        message.success("修改成功，即将跳转商品列表");
                        setTimeout(() => {
                            backGoodsList();
                        }, 1000);
                    }
                });
            } else {
                await createGoodsApi(data).then(res => {
                    if (res.code === 200) {
                        message.success("添加成功，即将跳转商品列表");
                        setTimeout(() => {
                            backGoodsList();
                        }, 1000);
                    }
                });
            }
            initEditForm();
        };
        const backGoodsList = () => {
            const { page, pageSize } = route.query;
            const routeLocationRaw = { name: "goods" };
            if (page && pageSize) {
                routeLocationRaw.query = {
                    page,
                    pageSize,
                };
            }
            router.replace(routeLocationRaw);
        };
        return {
            ...toRefs(state),
            handleSubmit,
            goodsTypeChange,
            backGoodsList,
        };
    },
});
</script>

<style scoped lang="scss">
.goods {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-bottom: 30px;
    .MenuContent {
        flex-grow: 1;
        padding-top: 30px;
        overflow-y: scroll;
    }
}
</style>
